<template>
    <!-- 更新危大工程管控计划 -->
    <base-breadcrumb :breadcrumb="!isAudit">
        <a-card :bordered="false">
            <div class="page-header table-page-search-wrapper">
                <title-name :title="pageType === 'look' ? '信息详情' : '基本信息'" />
                <a-form-model ref="form" :model="formInfo" :rules="rules">
                    <a-row :gutter="24">
                        <a-col :md="8" :sm="8">
                            <a-form-model-item
                                label="所属分公司"
                                :labelCol="{ lg: { span: 5 }, sm: { span: 5 } }"
                                :wrapperCol="{ lg: { span: 18 }, sm: { span: 18 } }"
                                prop="branchComId"
                            >
                                <SelectSubCompany :disabled="isDisabled" v-model="formInfo.branchComId" />
                            </a-form-model-item>
                        </a-col>
                        <a-col :md="8" :sm="8">
                            <a-form-model-item
                                label="所属项目"
                                :labelCol="{ lg: { span: 5 }, sm: { span: 5 } }"
                                :wrapperCol="{ lg: { span: 18 }, sm: { span: 18 } }"
                                prop="projectId"
                            >
                                <SelectProject
                                    :disabled="isDisabled"
                                    :isSelf="pageType !== 'look'"
                                    v-model="formInfo.projectId"
                                    keyValue="branchComId"
                                    :form="formInfo"
                                    :clear-list="true"
                                />
                            </a-form-model-item>
                        </a-col>
                    </a-row>
                </a-form-model>
            </div>
        </a-card>
        <div class="page-body">
            <a-card :bordered="false">
                <title-name title="危大工程管控计划项" />
                <div class="table-operateors mb20" v-if="pageType !== 'look'">
                    <a-button type="primary" @click="handleUpdate('add')">添加计划项</a-button>
                </div>
                <s-table
                    :scroll="{ x: 2900 }"
                    ref="table"
                    size="default"
                    rowKey="id"
                    :columns="columns"
                    :data="loadData"
                    :alert="true"
                    show-size-changer
                    show-quick-jumper
                    :showPagination="false"
                >
                    <template slot="index" slot-scope="text, record, index">{{ index + 1 }}</template>
                    <template slot="operator" slot-scope="text, record, index">
                        <a class="base-btn" @click="handleUpdate('edit', record, index)">编辑</a>
                        <a-divider type="vertical" />
                        <a-popconfirm title="确定要删除?" @confirm="() => handleUpdate('delete', record, index)">
                            <a>删除</a>
                        </a-popconfirm>
                        <!-- <a class="base-btn" @click="handleUpdate('delete', record, index)">删除</a> -->
                    </template>
                </s-table>
            </a-card>
            <div class="tool-btns page-btn-right-top" v-if="pageType !== 'look'">
                <a-button
                    v-if="pageType !== 'add' && formInfo.auditStatus === 'DRAFT'"
                    type="danger"
                    @click="handleSave('DELETE')"
                    >删除草稿</a-button
                >
                <a-button
                    v-if="formInfo.auditStatus == 'REJECTED' || formInfo.auditStatus == 'PAST'"
                    type="primary"
                    :loading="loading.REJECTED"
                    @click="handleSave(formInfo.auditStatus)"
                    >保存</a-button
                >
                <a-button v-else type="primary" :loading="loading.DRAFT" @click="handleSave('DRAFT')"
                    >保存草稿</a-button
                >
                <!-- <a-button
                    v-if="formInfo.auditStatus != 'PAST'"
                    type="primary"
                    :loading="loading.DRAFT"
                    @click="handleSave('DRAFT')"
                    >保存草稿</a-button
                > -->
                <a-button type="primary" :loading="loading.SUBMITTED" @click="handleSave('SUBMITTED')">提交</a-button>
                <a-button type="primary" @click="handleClose">关闭</a-button>
            </div>
            <div class="tool-btns page-btn-right-top" v-else>
                <a-button type="primary" @click="handleClose"  v-if="checkVisibleInDetail">关闭</a-button>
            </div>
        </div>
        <update-plan
            v-if="visible.updatePlan"
            @cancel="visible.updatePlan = false"
            @confirm="handleUpdateConfirm"
            :init-data="childInitData"
        />
    </base-breadcrumb>
</template>

<script>
import UpdatePlan from './UpdatePlan.vue'
import { STable } from '@/components'
import {
    getControlPlanDetail,
    getAuditControlPlanDetail,
    updateControlPlan,
    addControlPlan,
    deleteControlPlan,
} from '@/api/safetySupervision/projectControlPlan.js'
import SelectSubCompany from '@/components/Select/SelectSubCompany' // 分公司
import SelectProject from '@/components/Select/SelectProject' // 项目
import {  checkVisibleInDetail} from '@/utils/util'
const columns = [
    {
        title: '序号',
        dataIndex: 'index',
        scopedSlots: { customRender: 'index' },
    },
    {
        title: '危大工程类别',
        dataIndex: 'projectType.name',
    },
    {
        title: '级别',
        dataIndex: 'projectLevel.name',
    },
    {
        title: '危大工程具体情况',
        dataIndex: 'detailInfo',
        width: '20%',
        ellipsis: true,
    },
    {
        title: '施工部位',
        dataIndex: 'constructionSiteDesc',
    },
    // {
    //     title: '工程情况',
    //     dataIndex: 'situation',
    // },
    {
        title: '可能导致的事故',
        dataIndex: 'possibleAccidents',
        width: '20%',
        ellipsis: true,
    },
    {
        title: '计划控制措施（具有操作性）',
        dataIndex: 'controlMeasures',
        width: '20%',
        ellipsis: true,
    },
    {
        title: '责任部门/人',
        dataIndex: 'respEmployeeName',
    },
    {
        title: '开始时间',
        dataIndex: 'startDate',
    },
    {
        title: '结束时间',
        dataIndex: 'endDate',
    },
    {
        title: ' 操作',
        dataIndex: 'operator',
        width: '130',
        fixed: 'right',
        scopedSlots: { customRender: 'operator' },
    },
]
export default {
    name:'a'+Date.now(),    components: {
        STable,
        UpdatePlan,
        SelectSubCompany,
        SelectProject,
    },
    data() {
        return {
            checkVisibleInDetail:checkVisibleInDetail(this),
            childInitData: {},
            loading: {
                DELETE: false,
                DRAFT: false,
                SUBMITTED: false,
                REJECTED: false,
            },
            visible: {
                updatePlan: false,
            },
            formInfo: {
                itemVO: [],
            },
            columns: columns,
            queryParam: {},
            loadData: (parameter) => {
                const requestParameters = Object.assign({}, parameter, this.queryParam)
                return new Promise((resolve, reject) => {
                    resolve({
                        data: this.tableList,
                    })
                })
            },
            rules: {
                branchComId: [{ required: true, message: '请选择', trigger: 'change' }],
                projectId: [{ required: true, message: '请选择', trigger: 'change' }],
            },
        }
    },
    computed: {
        pageType() {
            return this.$route.query.pageType || 'look'
        },
        isDisabled() {
            return this.pageType === 'look'
        },
        tableList() {
            return this.formInfo.itemVO || []
        },
    },
    props: {
        isAudit: {
            // 是否作为审批详情
            type: Boolean,
            default: false,
        },
    },

    watch: {
        isAudit: {
            immediate: true,
            handler(val) {
                if (val) {
                    this.$nextTick(() => {
                        this.pageType = 'look'
                    })
                }
            },
        },
        pageType: {
            immediate: true,
            handler(val) {
                if (val === 'look') {
                    this.columns = this.columns.slice(0, -1)
                }
            },
        },
    },
    created() {
        this.getDetail()
    },
    methods: {
        // 计划项确认
        handleUpdateConfirm(data) {
            console.log(data)
            this.visible.updatePlan = false
            const { pageType, dataIndex } = data
            if (pageType === 'edit') {
                this.formInfo.itemVO.splice(dataIndex, 1, { ...data })
            } else {
                this.formInfo.itemVO.push({ ...data })
            }
        },
        async deleteControlPlan(params) {
            const [err, res] = await deleteControlPlan(params)
            if (!err) {
                this.$message.success('删除成功')
                this.handleClose()
            }
        },
        // 处理增、删、改操作
        handleSave(status) {
            this.$refs.form.validate(async (valid) => {
                if (!valid) return
                if (!this.tableList.length) {
                    // this.$message.error('请添加计划项')
                    this.$message.warning('请添加计划项')
                    return
                }
                if (this.loading[status]) return

                const params = {
                    ...this.formInfo,
                    itemDTO: this.formInfo.itemVO.map((item) => {
                        return { ...item, projectLevelId: item.projectLevel.id, projectTypeId: item.projectType.id }
                    }),
                    auditStatus: status,
                    id: this.$route.query.id || void 0,
                }

                const { pageType } = this.$route.query
                const fn = pageType === 'edit' ? updateControlPlan : addControlPlan
                const map = {
                    DRAFT: fn,
                    SUBMITTED: fn,
                    REJECTED: fn,
                }
                if (status == 'DELETE') {
                    let that = this
                    this.$confirm({
                        title: '温馨提示',
                        content: '确定是否删除数据？',
                        okText: '确认',
                        okType: 'danger',
                        cancelText: '取消',
                        onOk: () => {
                            let data = this.$clone(params)
                            delete data.itemVO
                            delete data.itemDTO
                            return that.deleteControlPlan(data)
                        },
                    })
                } else {
                    this.loading[status] = true
                    const [err, res] = await map[status](params)
                    if (!err) {
                        this.$message.success('保存成功')
                        this.handleClose()
                    }
                    this.loading[status] = false
                }
            })
        },
        async getDetail() {
            const { id } = this.$route.query
            if (!id) return
            const params = {
                id,
            }
            if (this.isAudit) {
                const [err, res] = await getAuditControlPlanDetail(params)
                if (!err) {
                    this.formInfo = {
                        ...this.formInfo,
                        ...res.data,
                        itemDTO: res.data.itemVO,
                        projectId: res.data.projectId.toString(),
                    }
                    this.$refs.table.refresh(true)
                    this.$nextTick(() => {
                        this.formInfo.projectId = res.data.projectId.toString()
                    })
                }
            }
            const [err, res] = await getControlPlanDetail(params)
            if (!err) {
                this.formInfo = {
                    ...this.formInfo,
                    ...res.data,
                    itemDTO: res.data.itemVO,
                    projectId: res.data.projectId.toString(),
                }
                this.$refs.table.refresh(true)
                this.$nextTick(() => {
                    this.formInfo.projectId = res.data.projectId.toString()
                })
            }
        },
        handleClose() {
            if (this.isAudit) {
                window.close()
            } else {
                this.$multiTab.close(this.$route.fullpath)
            }
        },
        // 处理更新操作（新增、编辑、删除）
        handleUpdate(type, data = {}, index = -1) {
            if (type === 'delete') {
                this.tableList.splice(index, 1)
                return
            }
            this.childInitData = {
                ...data,
                pageType: type,
                dataIndex: index,
                projectId: this.formInfo.projectId,
            }
            this.visible.updatePlan = true
        },
    },
}
</script>

<style lang="less" scoped>
@deep: ~'>>>';
.page-header {
    .header-row {
        display: flex;
        .flex-content {
            flex: auto;
        }
        .divider {
            margin: 0 12px;
        }
        .expand-btn {
            margin-left: 8px;
            font-size: 14px;
        }
    }
}
.page-body {
    .table-operateors {
        .ant-btn + .ant-btn {
            margin-left: 12px;
        }
    }
}
.tool-btns {
    display: flex;
    justify-content: flex-end;
    @{deep} .ant-btn + .ant-btn {
        margin-left: 12px;
    }
}
</style>